package com.easyfun.healthmagicbox.comm;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;

import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.json.ReferenceDataListJsonWrapper;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.DataReferenceDescription;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.j256.ormlite.dao.Dao;

public class ReferenceDataDescriptionDownloadTask extends BaseCommTask implements DatabaseAccess{

	

	public ReferenceDataDescriptionDownloadTask(Context context,
			CommCallback callback) {

		super(context,callback);

	}
	

	@Override
	public void run() {
		try {

			Dao<DataReferenceDescription, Integer> referenceDataDao = getHelper(mcontext)
					.getReferenceDataDao();

			long max = referenceDataDao
					.queryRawValue(
								"select max(syncid) from DataReferenceDescription");

			if (max > -1) {

				JSONObject serializedObj = new JSONObject();
				Map<String, String> parmas = new HashMap<String, String>();
				parmas.put("jsonstring", serializedObj.toString());

				String result = super.uploadByHTTP(parmas,
						ConstantData.ReferenceDataListDownloadURI);/*we need to change the url to reference data*/

				if (ServerResponseCode.parseOf(result)==ServerResponseCode.FAILED) {
					ccb.setCommResult(this,
							null, ServerResponseCode.FAILED);
					return;
				}
				if (ServerResponseCode.parseOf(result)==ServerResponseCode.NOMORE) {
					ccb.setCommResult(this,
							null, ServerResponseCode.NOMORE);
					return;
				}

				if (result.length()>0) {
					String[] ids = result.split("\\,");
					//find out the updated one
					for(String id : ids)
					{
						queryReferenceDataDescription(referenceDataDao, Integer.valueOf(id));
					}
					
					ccb.setCommResult(this,
							null, ServerResponseCode.SUCCESS);
				}else
				{
					ccb.setCommResult(this,
							null, ServerResponseCode.FAILED);
				}

				return;
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			if(e instanceof UnknownHostException) {
				ccb.setCommResult(this, null, ServerResponseCode.NOCONNECTION);
			}else {
			ccb.setCommResult(this, null,
					ServerResponseCode.FAILED);
			}
		} 

	}

	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(mcontext);
	}
	
	private void queryReferenceDataDescription(Dao<DataReferenceDescription, Integer>referenceDataDao, Integer referenceDataID)
	{
		try
		{
			List<DataReferenceDescription> data = referenceDataDao.queryForEq("syncId", referenceDataID.intValue());
			if(data.size() == 0)
			{ //new one							
				//ask server for data			
				Map<String, String> parameter = new HashMap<String, String>();
				parameter.put("jsonstring", referenceDataID.toString());
				
				String result = super.uploadByHTTP(parameter,
						ConstantData.ReferenceDataDownloadURI);/*we need to change the url to reference data*/
	
				if (ServerResponseCode.parseOf(result)==ServerResponseCode.FAILED) {
					ccb.setCommResult(this,
							null, ServerResponseCode.FAILED);
					return;
				}
				else if (ServerResponseCode.parseOf(result)==ServerResponseCode.NOMORE) {
					ccb.setCommResult(this,
							null, ServerResponseCode.NOMORE);
					return;
				}
				
				if (result.length()>0) 
				{
					ReferenceDataListJsonWrapper<?> wrapper = ReferenceDataListJsonWrapper
							.getInstance(result,ReferenceDataListJsonWrapper.class);
				
					referenceDataDao.create(wrapper.getMpps().get(0));
				}
			}
		}catch(Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			if(e instanceof UnknownHostException) {
				ccb.setCommResult(this, null, ServerResponseCode.NOCONNECTION);
			}else {
			ccb.setCommResult(this, null,
					ServerResponseCode.FAILED);
			}
		}
	}

}
